// pages/login/login.js
const http=require("../../api/http");
Page({

  /**
   * 页面的初始数据
   */
  // isregister为1是登录
  data: {
      isregister:false,
      username:'',
      password:'',
      repassword:'',
      picture:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.setData(
      {
        isregister: options.isregister == 0
      }
    )
  },

// 输入赋值
  getUserdata(e)
  {
    if(e.currentTarget.dataset.type=='account')
    {
      this.setData({
        username:e.detail.value,
      })
    }
    else if(e.currentTarget.dataset.type=='password')
    {
      this.setData({
        password:e.detail.value,
      })
    }
  },
// 登录注册接口
  handleLoginOrRegister(e) {

    if (this.data.username.trim()=='') {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }
    if (this.data.password === '') {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    if(this.data.repassword !=this.data.password)
    {
      wx.showToast({
        title:'密码验证失败',
        icon:'none'
      })
    }

    console.log("isregister == " + this.data.isregister);
    var page = this
    var params = {
      url: this.data.isregister ?'/user/login' :'/user/register' ,
      method: "POST",
      data: {
        username: this.data.username,
        password: this.data.password
      },
    callBack(res) {
      console.log(res);
      wx.setStorageSync('token', res.accessToken)
      if (this.data.isregister) {
        // 注册成功
        this.setData({
          username: '',
          password: '',
          repassword:'',
          isregister: !this.data.isregister
        })
      } else {
        // 登录成功
        // 跳转首页
        wx.switchTab({
          url: '../index/index',
        })
      }


    },
    errCallBack(res) {}
    }
    console.log(params);
    http.request(params)
  },

  // 返回首页
  goToindex()
  {
    wx.switchTab({
      url: '../index/index'
    })
  },

  // 登录注册之间跳转
  changeLoginOrRegister() {
    let str = this.data.isregister ? '1' : '0'
    wx.redirectTo({
      url: '/pages/login/login?isregister=' + str,
    })
  },

})